package com.nowcoder.work.community.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Data
@Component
public class CosUtil {

    @Value("${tencent.cloud.oss.secretId}")
    private static String secretId = "AKIDc2oNioHuwnPxIuuuUr55ybz88yYxDu51";

    @Value("${tencent.cloud.oss.secretKey}")
    private static String secretKey = "yjQsNkHdmokz162mLjv20qWy76vWs8CP";

    @Value("${tencent.cloud.oss.region}")
    private static String region = "ap-guangzhou";

    @Value("${tencent.cloud.oss.bucketName}")
    private static String photoBucket = "wii-dev-door-1252759886";

    /**
     * 初始化CosClient相关配置， appid、accessKey、secretKey、region
     */
    public static COSClient getCosClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        return new COSClient(cred, clientConfig);
    }

    /**
     * 上传文件
     */
    public static String uploadFile(MultipartFile file) throws IOException {
        //上传至存储桶的名字
        String KEY = "/" + file.getOriginalFilename();
        //将图片的具体信息传入ObjectMetadata类
        ObjectMetadata meta = new ObjectMetadata();
        //必须设置该属性
        meta.setContentLength(file.getSize());
        //设置字符编码格式
        meta.setContentEncoding("UTF-8");
        //获得文件后缀名并根据传入的图片格式设置ContentType
        PutObjectRequest putObjectRequest = new PutObjectRequest(photoBucket, KEY, file.getInputStream(), meta);
        putObjectRequest.setStorageClass(StorageClass.Standard);
        COSClient client = getCosClient();
        try {
            client.putObject(putObjectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭客户端
        client.shutdown();
        //拼接获得存储桶中可访问的地址
        return "https://" + photoBucket + ".cos." + region + ".myqcloud.com" + KEY;
    }

}
